using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Db4objects.Db4o;
using System.Data;
using MonitorTemperatura.Entidades;


namespace MonitorTemperatura.DataAccess
{
    public class UnidadDAO
    {

        private IObjectContainer OpenFileRemote()
        {
            IObjectContainer db = Db4oFactory.OpenClient(Util.HOST, Util.PORT, Util.USER, Util.PASS);
            return db;
        }

        private IObjectContainer OpenFile()
        {
           IObjectContainer db = Db4oFactory.OpenFile(Util.YapFileName);

           return db;
        }

        private void CloseFile(IObjectContainer db)
        {
            db.Close();
        }

        public void GrabarUnidad(Unidad obj)
        {
            IObjectContainer db = OpenFileRemote();
            db.Store(obj);
            CloseFile(db);
        }

        public DataTable ObtenerUnidades()
        {
            IObjectContainer db = OpenFileRemote();
            Unidad filtro = new Unidad();
            IObjectSet list = db.QueryByExample(filtro);            
            DataTable t = GetDataTable(list);
            CloseFile(db);
            return t;
        }

        private DataTable GetDataTable(IObjectSet result)
        {
            DataTable t = new DataTable();
            DataColumn c1 = new DataColumn("IdUnidad", typeof(string));
            DataColumn c2 = new DataColumn("Descripcion", typeof(string));
            t.Columns.Add(c1);
            t.Columns.Add(c2);
            if (result.Count > 0)
            {
                foreach (object obj in result)
                {
                    DataRow r = t.NewRow();
                    r["IdUnidad"] = ((Unidad)obj).IdUnidad;
                    r["Descripcion"] = ((Unidad)obj).NombreUnidad;
                    t.Rows.Add(r);
                }
            }
            return t;
        }
    }
}
